<template>
  <div class="datatable">
    <basic-container >
      <el-row :span="24" >
        <el-col :xs="24"
                :sm="24"
                :md="24"
                class="datatable__main">
          <chc-datagrid :option="option"
                     ref="crud"
                     v-model="form"
                     @on-load="getList"
                     :table-loading="listLoading"
                     @search-change="onSearch"
                     @refresh-change="onRefresh"
                     @current-row-change="onCurrentRowChange"
                     :data="list"
                     :style="{height:'100%'}"
                      >
            <template slot="menuLeft">
              <el-button v-if="permissions['datatable.add']"
                         class="filter-item"
                         @click="onCreateDlgOpen"
                         size="small"
                         type="primary"
                         icon="el-icon-plus">创建
              </el-button>
              <el-button v-if="permissions['datatable.add']"
                         class="filter-item"
                         @click="onCopyDlgOpen"
                         size="small"
                         type="primary"
                         :disabled="!(currentRow&&currentRow.id)"
                         icon="el-icon-plus">复制
              </el-button>
            </template>
            <template slot="menu"
                      slot-scope="scope">
              <el-button
                         class="filter-item"
                         @click="onEditDlgOpen(scope.row,scope.index,true)"
                         size="small"
                         type="text"
                         icon="el-icon-edit">查看
              </el-button>
              <el-button v-if="permissions['datatable.edit']&&!scope.row.system"
                         class="filter-item"
                         @click="onEditDlgOpen(scope.row,scope.index,false)"
                         size="small"
                         type="text"
                         icon="el-icon-edit">编辑
              </el-button>
              <el-button v-if="permissions['datatable.delete']&&!scope.row.system"
                         class="filter-item"
                         @click="onDelete(scope.row,scope.index)"
                         size="small"
                         type="text"
                         icon="el-icon-delete">删除
              </el-button>
              <el-button
                         size="small"
                         type="text"
                         icon="el-icon-menu"
                         @click="onDatatableOpen(scope.row,scope.index)">生成界面
              </el-button>
              <!-- <br>
              <el-button
                         size="small"
                         type="text"
                         icon="el-icon-edit"
                         @click="onAVueCode(scope.row,scope.index)">AVue代码
              </el-button>
              <el-button
                         size="small"
                         type="text"
                         icon="el-icon-menu"
                         @click="onMenuCode(scope.row,scope.index)">菜单代码
              </el-button> -->
              <!-- <el-button
                         size="small"
                         type="text"
                         icon="el-icon-menu"
                         @click="handleDatatableCode(scope.row,scope.index)">数据表格xml
              </el-button> -->
            </template>
          </chc-datagrid>
          <!--<chc-datagrid :option="fieldOption"
                     ref="fieldCrud"
                     v-model="fieldForm"
                     :data="fieldList"
                     :style="{height:'40%'}"
                     >
          </chc-datagrid>-->
        </el-col>
      </el-row>
    </basic-container>
    <el-dialog title="代码显示"
               :visible.sync="codeDlg.visible">
      <el-input type="textarea"
               v-model="codeDlg.code"
               :autosize="{ minRows: 20, maxRows: 20}">
      </el-input>
      <div slot="footer"
           class="dialog-footer">
        <el-button type="primary"
                   @click="onCodeDlgClose()">关闭
        </el-button>
      </div>
    </el-dialog>
    <el-dialog title="创建表格" :visible.sync="createDlg.visible" :close-on-click-modal="false" width="80%">
      <el-form :model="createDlg.form"
                :rules="createDlg.rules"
                ref="createBySqlForm"
                label-width="100px">
        <el-form-item label="表格ID"
                      prop="id">
          <el-input type="text"
                    v-model="createDlg.form.id"
                    auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="表格名称"
                      prop="title">
          <el-input type="text"
                    v-model="createDlg.form.title"
                    auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="是否只读"
                      prop="readOnly">
          <el-switch v-model="createDlg.form.readOnly"></el-switch>
        </el-form-item>
        <el-form-item label="备注"
                      prop="remark">
          <el-input type="text"
                    v-model="createDlg.form.remark"
                    auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="查询语句"
                      prop="sql">
          <el-input type="textarea"
                    v-model="createDlg.form.sql"
                    auto-complete="off"
                    :autosize="{ minRows: 15, maxRows: 15}"
                    ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary"
                    @click="onCreateDlgConfirm()">确认
        </el-button>
        <el-button @click="onCreateDlgCancel()">取消</el-button>
      </div>

    </el-dialog>
    <el-dialog title="复制表格" :visible.sync="copyDlg.visible" width="50%" :close-on-click-modal="false">
      <el-form :model="copyDlg.form"
                :rules="copyDlg.rules"
                ref="copyForm"
                label-width="100px">
        <el-form-item label="新表格ID"
                      prop="id">
          <el-input type="text"
                    v-model="copyDlg.form.id"
                    auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="新表格名称"
                      prop="title">
          <el-input type="text"
                    v-model="copyDlg.form.title"
                    auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="备注"
                      prop="remark">
          <el-input type="text"
                    v-model="copyDlg.form.remark"
                    auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary"
                    @click="onCopyDlgConfirm()">确认
        </el-button>
        <el-button @click="onCopyDlgCancel()">取消</el-button>
      </div>

    </el-dialog>
    <el-dialog title="编辑表格"
               :visible.sync="editDlg.visible" width="80%" :close-on-click-modal="false">
      <el-input type="textarea"
               v-model="editDlg.form.content"
               :readonly="editDlg.readOnly"
               :autosize="{ minRows: 20, maxRows: 20}">
      </el-input>
      <div slot="footer"
           class="dialog-footer">
        <el-button v-if="!editDlg.readOnly" type="primary"
                   @click="onEditDlgConfirm()">保存
        </el-button>
        <el-button v-if="!editDlg.readOnly" @click="onEditDlgCancel()">取消</el-button>
        <el-button v-if="editDlg.readOnly" type="primary"
                   @click="onEditDlgCancel()">关闭
        </el-button>

      </div>
    </el-dialog>

  </div>

</template>

<script>
  import {queryDataTable,getAVueOptionCode,getMenuCode,getDataTableCode,
    createDataTableBySql,createDataTable,updateDataTable,deleteDataTable,copyDataTable} from "@/components/chc-ui/api/data-table";
  import {tableOption,fieldTableOption} from './table-option.js';
  import {mapGetters} from "vuex";
  import {constants} from 'fs';
  import {connect} from 'tls';

  export default {
    name: "datatable",
    data() {
      return {
        option: tableOption,
        // page: {
        //   total: 0, // 总页数
        //   currentPage: 1, // 当前页数
        //   pageSize: 20, // 每页显示多少条,
        //   isAsc: false//是否倒序
        // },
        list: [],
        listLoading: true,
        form: {
        },
        currentRow: undefined,
        fieldOption: fieldTableOption,
        fieldList: [],
        fieldForm: {
        },
        codeDlg:{
          visible:false,
          code:''
        },
        createDlg: {
          visible : false,
          form: {
            id: '',
            title: '',
            remark:'',
            sql: ''
          }
        },
        copyDlg: {
          visible : false,
          form: {
            id: '',
            title: '',
            remark:''
          }
        },
        editDlg: {
          visible : false,
          readOnly : false,
          form: {
            id: '',
            content: ''
          }
        }
      };
    },
    computed: {
      ...mapGetters(["permissions"])
    },
    methods: {
      getList(page, params) {
        this.listLoading = true;
        queryDataTable(
          Object.assign({
            current: page.currentPage,
            size: page.pageSize
          }, params)
        ).then(response => {
          this.list = response.data.data.records;
					this.$refs.crud.tablePage.total = response.data.data.total
          this.listLoading = false;
        }).catch(error=>{
          this.listLoading = false;
				});
      },

      onSearch(param) {
				this.$refs.crud.tablePage.currentPage = 1;
        this.getList(this.$refs.crud.tablePage, param);
      },
      onRefresh() {
        this.getList(this.$refs.crud.tablePage)
      },
      onAVueCode(row, index) {
        getAVueOptionCode(row.id,true).then(response=>{
          this.codeDlg.code = JSON.stringify(response.data, null, 4);
          this.codeDlg.visible=true;
        });
      },
      onMenuCode(row, index) {
        getMenuCode(row.id).then(response=>{
          this.codeDlg.code = JSON.stringify(response.data, null, 4);
          this.codeDlg.visible=true;
        });
      },
      onDatatableCode(row, index) {
        getDataTableCode(row.id).then(response=>{
          this.codeDlg.code = response.data;
          this.codeDlg.visible=true;
        });
      },
      onCodeDlgClose(){
        this.codeDlg.visible=false;
      },
      onDatatableOpen(row,index){
        this.$router.push({
            path:'/dataGrid/'+row.id,
            query:{
              name: row.title
            }
          });
      },

      setCurrent(row) {
          this.$refs.crud.setCurrentRow(row);
        },
      onCurrentRowChange(val){
        if (val)
          this.fieldList = val.fields;
        else
          this.fieldList = [];
        this.currentRow= val;
      },
      onCreateDlgOpen() {
        this.createDlg.form = {id:'',title:'',remark:'',sql:''};
        this.createDlg.visible=true;
      },
      onCreateDlgConfirm() {
        createDataTableBySql(this.createDlg.form).then(response=>{
          this.list.splice(0, 0, response.data.data);
          this.$refs.crud.setCurrentRow(response.data.data);
          this.createDlg.visible=false;
          this.$notify({
            title: "成功",
            message: "创建成功",
            type: "success",
            duration: 2000
          });
        });

      },
      onCreateDlgCancel() {
        this.createDlg.visible=false;
      },
      onCopyDlgOpen() {

        this.copyDlg.form = {id:'',title:'',remark:''};
        this.copyDlg.visible=true;
      },
      onCopyDlgConfirm() {
        if (!this.currentRow.id){
          this.$notify({
            title: "错误",
            message: "请选择一个源表格！",
            type: "error",
            duration: 2000
          });
          return;
        }
        copyDataTable(this.currentRow.id,this.copyDlg.form).then(response=>{
          this.list.splice(0, 0, response.data.data);
          this.$refs.crud.setCurrentRow(response.data.data);
          this.copyDlg.visible=false;
          this.$notify({
            title: "成功",
            message: "创建复制",
            type: "success",
            duration: 2000
          });
        });

      },
      onCopyDlgCancel() {
        this.copyDlg.visible=false;
      },
      onEditDlgOpen(row, index, readOnly) {
        if (row.system&&!readOnly){
          //系统内置表格不能删除
          this.$notify({
            title: "错误",
            message: "不能编辑系统内置表格！",
            type: "error",
            duration: 2000
          });
          return;
        }
        getDataTableCode(row.id).then(response=>{
          this.editDlg.readOnly=readOnly;
          this.editDlg.form = {id:row.id,content:response.data};
          this.editDlg.index = index;
          this.editDlg.visible=true;
        });

      },
      onEditDlgConfirm(){
        updateDataTable(this.editDlg.form.id,{content:this.editDlg.form.content}).then(response=>{
          this.$set(this.list, this.editDlg.index, response.data.data);
          this.$refs.crud.setCurrentRow(response.data.data);
          this.editDlg.visible=false;
          this.$notify({
            title: "成功",
            message: "更新成功",
            type: "success",
            duration: 2000
          });
        });
      },
      onEditDlgCancel() {
        this.editDlg.visible=false;
      },
      onDelete(row, index) {
        if (row.system){
          //系统内置表格不能删除
          this.$notify({
            title: "错误",
            message: "不能删除系统内置表格！",
            type: "error",
            duration: 2000
          });
          return;
        }
        this.$confirm(
          "此操作将永久删除选中的记录, 是否继续?",
          "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }
        ).then(() => {
          deleteDataTable(row.id)
            .then(() => {
              this.list.splice(index, 1);
              this.$notify({
                title: "成功",
                message: "删除成功",
                type: "success",
                duration: 2000
              });
            })
            .cache((error) => {
              console.log(error);
              this.$notify({
                title: "失败",
                message: "删除失败: " + error,
                type: "error",
                duration: 2000
              });
            });
        });
      },

    }
  };
</script>
<style lang="scss">
  .datatable {
    height: 100%;

    &__tree {
      padding-top: 3px;
      padding-right: 10px;
    }

    &__main {
      .el-card__body {
        padding-top: 0;
      }
    }
  }
</style>

